package com.woke.fragment;


import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bean.Banner;
import com.bean.TabColumn;
import com.bean.UserWallet;
import com.bigkoo.alertview.AlertView;
import com.bumptech.glide.Glide;
import com.example.woke.ChannelActivateActivity;
import com.example.woke.HtmlActivity;
import com.example.woke.LoadActivity;
import com.example.woke.MoneyonlineActivity;
import com.example.woke.ReciverFActivity;
import com.example.woke.TixianActivity;
import com.example.woke1.CaixintongActivity;
import com.example.woke1.ZhcailicaiActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.http.HttpMethods;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;
import com.netease.nim.uikit.GlideApp;
import com.nova.lfh.zxing.RScannerActivity;
import com.rd.PageIndicatorView;
import com.woke.adapter.AdapterBannerPager;
import com.woke.adapter.OnItemClickListener;
import com.woke.adapter.TabHomeColumnViewProvider;
import com.woke.addressactivity.ExChangeActivity;
import com.woke.addressactivity.Userinfo_xiaActivity;
import com.woke.addressactivity.UserpromoteActivity;
import com.woke.data.Datas_event2;
import com.woke.method.ImageHandler;
import com.woke.method.MyApp;
import com.woke.serizedatas.Datas_load;
import com.wokeMy.view.CongziPassActivity;
import com.wokeMy.view.CreditCardActivity;
import com.wokeMy.view.LotteryMainActivity;
import com.wokeMy.view.ZhiqingSelectActivity;
import com.wokeMy.view.adpter.NewsAdapter;
import com.wokeMy.view.model.Constant;
import com.wokeMy.view.model.News;
import com.wokeMy.view.turui.MyRealNameActivity;
import com.wokeMy.view.util.Util;
import com.wokeMy.view.util.ViewTools;
import com.wokeMy.view.view.RoundImageView;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

import static com.zhongcai.online.R.mipmap.ic_tabhome_wallet;
import static me.drakeet.multitype.MultiTypeAsserts.assertAllRegistered;
/**
 * 首页
 */
public class TabHomeFragment extends BaseFrag implements XRecyclerView.LoadingListener , View.OnClickListener {

    private View rootView;
    private XRecyclerView mRecyclerView;
    private MultiTypeAdapter mMulitypeAdapter;
    private ViewPager mViewPager;
    private PageIndicatorView mPageIndicatorView;
    private ImageView jin_home_iv,xiala_main_iv;
    RoundImageView touxiangIV;
    private TextView yuMTv,shouTv,name_home_tv,chongzi_home_tv,tixian_home_tv,lev_home_tv;
    private ImageHandler mHandler;
    private AdapterBannerPager mBannerAdapter;
    private List<Banner> mBannerList = new ArrayList<>();
    private String[] mColumnTitles;
    private  String[] mColumnRemarkd;
    private TypedArray typedArray;
    private NewsAdapter newsAdapter;
    private ListView newLv;

    private MyApp application;
    private Datas_load loaded;
    int user_from;
    String status,version,first; // 系统开关 0关 1开
    private SharedPreferences sharep;
    PackageInfo packInfo;
    ArrayList<News> newsData;
    Observer<UserWallet>    mWalletObserver = new Observer<UserWallet>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(UserWallet value) {
            Log.e("getUserInfo","mWalletObserver");
            if (value != null) {
                //				String money_f = getString (R.string.user_money_f);
                Log.e("money ", value.toString());
                String money_f = getResources().getString(R.string.user_money_f3);
                DecimalFormat ddf = new DecimalFormat("0.00");
                ddf.setMaximumFractionDigits(2);
                ddf.setGroupingSize(0);
                ddf.setRoundingMode(RoundingMode.FLOOR);
                yuMTv.setText(ddf.format(value.getUser_money())+"元");
                shouTv.setText(String.format(money_f, ddf.format(value.getUser_proceeds())));

            }
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    };
    private PopupWindow popupWindow2 = null;//  PopupWindow在android.widget包下，弹出窗口的形式展示。官方文档对该控件的描述是：“一个弹出窗口控件，可以用来显示任意视图(View)，而且会浮动在当前 活动(activity)的顶部”。PopupWindow可以让我们实现多种自定义控件，例如：menu、alertdialog等弹窗似的View
    private LayoutInflater layoutInflater2;//为了获取res 下的layout的xml文件
    private View popView2;

    private AlertView alertView;
    Dialog dialog;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.e("TabHomeFragment","onCreateView");
        application = (MyApp) getActivity().getApplication();
        EventBus.getDefault().register(this);


        String appname=getResources().getString(R.string.oem_app_name);
        user_from=Constant.USER_FROM.get(appname);
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_tab_home, container, false);
            newLv=rootView.findViewById(R.id.news_lv);
            xiala_main_iv=(ImageView)rootView.findViewById(R.id.xiala_main_iv);
            View headerView = inflater.inflate(R.layout.adapter_banner_viewpager, container, false);
            mViewPager = (ViewPager) headerView.findViewById(R.id.banner_viewpager);
            mPageIndicatorView = (PageIndicatorView) headerView.findViewById(R.id.banner_pageIndicator);
            touxiangIV = (RoundImageView) headerView.findViewById(R.id.touxiang_home__iv);
            jin_home_iv = (ImageView) headerView.findViewById(R.id.jin_home_iv);
            lev_home_tv = (TextView) headerView.findViewById(R.id.lev_home_tv);
            yuMTv = (TextView) headerView.findViewById(R.id.yuM_home__tv);
            shouTv = (TextView) headerView.findViewById(R.id.shou_home__tv);
            name_home_tv = (TextView) headerView.findViewById(R.id.name_home_tv);
            tixian_home_tv = (TextView) headerView.findViewById(R.id.tixian_home_tv);
            chongzi_home_tv = (TextView) headerView.findViewById(R.id.chongzi_home_tv);
            newsData=new ArrayList<>();
            newsAdapter=new NewsAdapter(getContext(),newsData);
            newLv.setAdapter(newsAdapter);
            ViewTools.setListViewHeightBasedOnChildren(newLv);
            news();
            tixian_home_tv.setOnClickListener(this);
            chongzi_home_tv.setOnClickListener(this);
            xiala_main_iv.setOnClickListener(this);
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.icn__launch_oem);
            RoundedBitmapDrawable circularBitmapDrawable =
                    RoundedBitmapDrawableFactory.create(getResources(), bitmap);
            circularBitmapDrawable.setCircular(true);
            touxiangIV.setImageDrawable(circularBitmapDrawable);
                getBannerList();



                mRecyclerView = (XRecyclerView) rootView.findViewById(R.id.xRecyclerView);
                mRecyclerView.addHeaderView(headerView);
//            mRecyclerView.setFootView(news);

//            mRecyclerView.setFootView();
//                 View foot = inflater.inflate(R.layout.item_test, container, false);
//                TextView tv = new TextView(getContext());
//                tv.setText("footer");
//                tv.setTextColor(Color.BLACK);
//                mRecyclerView.setFootView(tv);

                mRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
                mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
                mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
                mRecyclerView.setLoadingListener(this);
            sharep = getContext().getSharedPreferences ("loaduser", Context.MODE_PRIVATE);
            status = sharep.getString ("status","");
            version = sharep.getString ("version","");
            Log.e("sharepsharep",status+"//"+version);
//            if (TextUtils.isEmpty(status)){
//                sysKguan();
//            }else {
//                initMulitypeAdapter();
//            }
                initMulitypeAdapter();
//                mRecyclerView.setNoMore(true);

            } else {
                ViewGroup parent = (ViewGroup) rootView.getParent();
                if (parent != null) {
                    parent.removeView(rootView);
                }


        }
        return rootView;
    }

    private void getUserInfo() {
        loaded = application.getDatas_load();
        if (null != loaded) {
            if (null != loaded.getCom_name() && !loaded.getCom_name().equals("")) {
                name_home_tv.setText(loaded.getCom_name());
            } else {
                if ("0".equals(loaded.getUser_nicename())) {

                } else {
                    name_home_tv.setText(loaded.getUser_nicename()+" ");
                }
            }

            if (!TextUtils.isEmpty(loaded.getAvatar())) {
                String avatar = loaded.getAvatar();
                if (!avatar.startsWith("http")) {
                    avatar = "http://" + avatar;
                }
                Log.e("UserFragment", "Glide" + avatar);
                GlideApp.with(this)
                        .load(avatar)
                        .placeholder(R.mipmap.icn__launch_oem)
                        .error(R.mipmap.icn__launch_oem)
                        .into(touxiangIV);
            }
            jin_home_iv.setVisibility(View.VISIBLE);
            lev_home_tv.setVisibility(View.VISIBLE);
            Log.e("TabHome",loaded.getUser_type());
            switch (loaded.getUser_type()) {
                case "2":
                    jin_home_iv.setBackgroundResource(R.mipmap.tong);
                    break;
                case "3":
                    jin_home_iv.setBackgroundResource(R.mipmap.yin_ioc);
                    break;
                case "4":
                    jin_home_iv.setBackgroundResource(R.mipmap.jin);
                    break;
                case "5":
                    jin_home_iv.setBackgroundResource(R.mipmap.hhr);
                    break;
                case "6":
                    jin_home_iv.setBackgroundResource(R.mipmap.tophhr);
                    break;
                default:
                    jin_home_iv.setBackgroundResource(R.mipmap.tong);
                    break;
            }
            lev_home_tv.setText(loaded.vipdescribe);
//            yuMTv.setText(Util.twoString(loaded.user_money)+"元");
//            shouTv.setText(Util.twoString(loaded.user_proceeds)+"元");
            //            String icon = loaded.icon;
//            if (!TextUtils.isEmpty(icon)) {
//                if (!icon.startsWith("http")) {
//                    icon = "http://" + icon;
//                }
//                Glide.with(this).load(icon).into(jin_home_iv);
//            }

        } else {
            jin_home_iv.setVisibility(View.GONE);
            lev_home_tv.setVisibility(View.GONE);
        }
    }

    private void getBannerList() {
        HttpMethods.getInstance().getBannerList(mBannersObserver,user_from);
//        Call<String> systemKg = HttpMethods.getInstance().getSystemKg(1, user_from);
//        systemKg.enqueue(new Callback<String>() {
//            @Override
//            public void onResponse(Call<String> call, Response<String> response) {
//            Log.e("onResponse",response.body());
//            }
//
//            @Override
//            public void onFailure(Call<String> call, Throwable t) {
//                Log.e("onResponse",call.toString());
//            }
//        });

    }

//    private void inittoolbar(View rootView) {
//        mToolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
//        mToolbarTitle = (TextView) rootView.findViewById(R.id.toolbar_title);
//        if (mToolbar != null) {
//            mToolbar.setTitle("");
//
//            mToolbar.inflateMenu(getMenuId());
//            //menu xml 使用actionLayout 自定义menu布局会导致setOnMenuItemClickListener事件失效
//            MenuItem menuItem = mToolbar.getMenu().findItem(R.id.scan);
//            menuItem.getActionView().setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    //跳转扫一扫
//                    if (getActivity() != null) {
//                        IntentIntegrator.forSupportFragment(TabHomeFragment.this).setCaptureActivity(RScannerActivity.class).initiateScan();
////                        new IntentIntegrator(getActivity()).setCaptureActivity(RScannerActivity.class).initiateScan();
//                    }
//                }
//            });
//            mToolbar.setNavigationIcon(null);
//
//        }
//    }



    @Override
    public void onResume() {
        super.onResume();
        Log.e("TabHomeFragment","onResume");
        getUserInfo();
        getmywallet();
        news();
        if (mHandler != null) {
            mHandler.setIsPause(false);
        }
    }

    @Override
    public void onPause() {
        Log.e("TabHomeFragment","onPause");
        super.onPause();
        if (mHandler != null) {
            mHandler.setIsPause(true);
        }
    }


    @Override
    public int getMenuId() {
        return R.menu.tabhome_scan;
    }

    @Override
    public void OnNavigationClickListener(View v) {

    }

    @Override
    public boolean OnMenuItemClickListener(MenuItem item) {
        return false;
    }

    @Override
    public void onRefresh() {
        getBannerList();
        mRecyclerView.refreshComplete();

    }

    @Override
    public void onLoadMore() {
        mRecyclerView.loadMoreComplete();
//        mRecyclerView.setNoMore(true);
    }


    private Observer<List<Banner>> mBannersObserver = new Observer<List<Banner>>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(List<Banner> value) {
            if (value != null) {
                Log.e("value",""+value);
                intViewPagerAndIndicator(value);
            }
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    };

    private void intViewPagerAndIndicator(List<Banner> list) {
        if (list != null && list.size() > 0) {
            mBannerList.clear();
            mBannerList.addAll(list);
        }
        if (mBannerAdapter == null) {
            mBannerAdapter = new AdapterBannerPager(mBannerList);
            Log.e("mBannerAdapter",mBannerList.toString());
            if (!mBannerList.get(0).getAd_url().equals("")){
                mBannerAdapter.setOnItemClickListener(mItemClickListener);
            }
            mViewPager.setAdapter(mBannerAdapter);
            mHandler = new ImageHandler(getContext());
        } else {
            mBannerAdapter.notifyDataSetChanged();
        }
        mPageIndicatorView.setCount(mBannerList.size());
        mPageIndicatorView.setViewPager(mViewPager);

        mHandler.setViewPage(mViewPager);
        mHandler.sendEmptyMessage(ImageHandler.MSG_UPDATE_IMAGER);
    }

    private void initMulitypeAdapter() {
        mRecyclerView.setPullRefreshEnabled(false);
        mRecyclerView.setLoadingMoreEnabled(false);
        mColumnTitles = getResources().getStringArray(R.array.tabhome_column_content);
        mColumnRemarkd = getResources().getStringArray(R.array.tabhome_column_content_remark);
        typedArray = getResources().obtainTypedArray(R.array.tabhome_column_icon);
        if (mColumnTitles.length != typedArray.length()) {
            throw new RuntimeException("title length != icons length");
        }
        Items mItems = new Items();

        for (int i = 0; i < mColumnTitles.length; i++) {
            TabColumn column = new TabColumn(typedArray.getResourceId(i, ic_tabhome_wallet), mColumnTitles[i], null);
            column.setRemark(mColumnRemarkd[i]);
            mItems.add(column);
        }
        typedArray.recycle();
//		BannerItems bannerItems = new BannerItems ();
//		List<Banner> banners = new ArrayList<> ();
//		for (int i = 0; i < 5; i++) {
//			banners.add (new Banner ());
//		}
//		bannerItems.setBanners (banners);
//		mItems.add (bannerItems);
//
        mMulitypeAdapter = new MultiTypeAdapter();
        mMulitypeAdapter.register(TabColumn.class, new TabHomeColumnViewProvider(mItemClickListener));
//
        mRecyclerView.setAdapter(mMulitypeAdapter);

        mMulitypeAdapter.setItems(mItems);
        mMulitypeAdapter.notifyDataSetChanged();
        if (mItems.size() > 0) {
            assertAllRegistered(mMulitypeAdapter, mItems);//执行这句话时,必须保证 Items.size()>0
        }
    }

    private OnItemClickListener mItemClickListener = new OnItemClickListener() {
        @Override
        public void OnItemClick(View view, int position) {

        }

        @Override
        public void OnItemClick(View view, Object object, int position) {
            if (object instanceof TabColumn) {
                MyApp application = (MyApp) getActivity().getApplication();
                if (application.getDatas_load() == null) {
                    aralogid("还未登录", "前往登录", 1);
                    return;
                }
                TabColumn column = (TabColumn) object;
                final Intent intent = new Intent();
                if (mColumnTitles[0].equals(column.getColumnName())) {
                    if (getContext() != null) {
                        //中财钱包
                        intent.setClass(getActivity(), ReciverFActivity.class);
                        startActivity(intent);
                    }
                } else if (mColumnTitles[1].equals(column.getColumnName())) {
                    if (getContext() != null) {
                        //中财彩票
                        intent.setClass(getActivity(), LotteryMainActivity.class);
                        startActivity(intent);
                    }
                } else if (mColumnTitles[2].equals(column.getColumnName())) {
                    if (mColumnTitles.length==2){
                        //财富通
                        intent.setClass(getActivity(), CaixintongActivity.class);
                        startActivity(intent);
                    }else {
                        //中财车险
                        int userid = Integer.parseInt(application.getDatas_load().getId());
                        if (userid > 0) {
                            HttpMethods.getInstance().fetchDirectUrl(carInsuranceObserver, userid);
                        }

                    }

                } else if (mColumnTitles[3].equals(column.getColumnName())) {
                    if (getContext() != null) {
                        //中财理财
                        intent.setClass(getActivity(), ZhcailicaiActivity.class);
                        startActivity(intent);
                    }
                } else if (mColumnTitles[4].equals(column.getColumnName())) {
                    //中交所的中 信用卡
                    intent.setClass(getActivity(), CreditCardActivity.class);
                    startActivity(intent);
                } else if (mColumnTitles[5].equals(column.getColumnName())) {
                    //人品贷 更换为网贷
                    intent.setClass(getActivity(), ExChangeActivity.class);
                    intent.putExtra("sort", 1);
                    startActivity(intent);
                } else if (mColumnTitles[6].equals(column.getColumnName())) {
                    if (getContext() != null) {
                        //中财借贷
                        intent.setClass(getActivity(), MoneyonlineActivity.class);
                        startActivity(intent);
                    }
                } else if (mColumnTitles[7].equals(column.getColumnName())) {
                    if (getContext() != null) {
                        //中交所
                        intent.setClass(getActivity(), ExChangeActivity.class);
                        startActivity(intent);
                    }
                } else if (mColumnTitles[8].equals(column.getColumnName())) {
                    //财富通
                    intent.setClass(getActivity(), CaixintongActivity.class);
                    startActivity(intent);
                }
            } else if (object instanceof Banner) {
                Banner banner = (Banner) object;
                if (getContext() != null) {
                    MyApp application = (MyApp) getActivity().getApplication();
                    int userid = 1;
                    if (null != application.getDatas_load()) {
                        userid = Integer.parseInt(application.getDatas_load().getId());
                    }
                    if (userid <= 0) {
                        userid = 1;
                    }
                    String encodeUserId = new String((Base64.encode(String.valueOf(userid).getBytes(), Base64.DEFAULT)));
                    Intent intent = new Intent(getContext(), HtmlActivity.class);
                    intent.putExtra("urlname", banner.getAd_name());
                    if (banner.getAd_url().contains("cd.webportal.cc/")){
                        intent.putExtra("url", banner.getAd_url());
                    }else {
                        intent.putExtra("url", banner.getAd_url() + "/NOxBL7xp/" + encodeUserId);
                    }

                    getContext().startActivity(intent);
                }
            }
        }
    };
    AlertDialog alertDialog;

    private void aralogid(String info, String kll, final int ppp) {
        alertDialog = new AlertDialog.Builder(getActivity()).
                setTitle(info).
                setMessage(kll).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent();
                        if (ppp == 1) {
                            intent.setClass (getActivity(),
                                    LoadActivity.class);
                            startActivity (intent);
                        } else if (ppp == 2) {
                            intent.setClass (getActivity(),
                                    MyRealNameActivity.class);
                            startActivity (intent);
                        }
                    }
                }).
                setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        alertDialog.dismiss();
                    }
                }).create();
        alertDialog.show();
    }
//    private void aralogid(String info, String kll, final int ppp) {
//        alertView = new AlertView(info, kll, "取消", new String[]{"确定"}, null, getContext(), AlertView.Style.Alert, new com.bigkoo.alertview.OnItemClickListener() {
//            @Override
//            public void onItemClick(Object o, int i) {
////                Toast.makeText(getContext(),i+"",Toast.LENGTH_SHORT).show();
//                switch (i) {
//                    case -1:
//                        alertView.dismiss();
//                        break;
//                    case 0:
//                    Intent intent = new Intent();
//                    if (ppp == 1) {
//                        intent.setClass (getActivity(),
//                                LoadActivity.class);
//                        startActivity (intent);
//                    } else if (ppp == 2) {
//                        intent.setClass (getActivity(),
//                                RealnameActivity.class);
//                        startActivity (intent);
//                    }
//                        break;
//                    default:
//                        break;
//                }
//            }
//        });
//        alertView.show();
//    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //接收扫码
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (getContext() == null) return;
            if (TextUtils.isEmpty(result.getContents())) {
            } else {
                String serialNum = getserialNumberFromUrl(result.getContents());
                if (!TextUtils.isEmpty(serialNum)) {
                    //商家激活码
                    MyApp application = (MyApp) getActivity().getApplication();

                    if (null != application.getDatas_load()) {
                        int userId = Integer.parseInt(application.getDatas_load().getId());
                        HttpMethods.getInstance()
                                .activateSeriesNo(mActivateObserver, userId, serialNum);
                    }

                } else {
                    String qrCode = result.getContents();
                    Log.e("qrCode",qrCode);
                    if (!TextUtils.isEmpty(qrCode)) {
                        if (qrCode.length() > 0) {
                            ldScan(qrCode);
//                            Intent intent = new Intent(getContext(), ZhongcaiReciveActivity.class);
//                            intent.putExtra("result", result.getContents());
//                            startActivity(intent);
//                            Toast.makeText(getContext(), result.getContents(), Toast.LENGTH_SHORT)
//                                    .show();
                        }
                    }

                }
            }
        } else {
            // This is important, otherwise the result will not be passed to the fragment
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * 截取链接上的 的serialNumber值
     * &serialNumber=42b26142ca6f180d
     *
     * @param urlStr
     * @return
     */
    private String getserialNumberFromUrl(String urlStr) {
        Pattern p = Pattern.compile("&serialNumber=[A-Za-z0-9]+");
        Matcher m = p.matcher(urlStr);
        if (m.find()) {
            String[] split = m.group().split("=");
            return split[1];
        }
        return "";
    }

    private Observer<String> mActivateObserver = new Observer<String>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(String serialNum) {
            if (!TextUtils.isEmpty(serialNum)) {
                if (getContext() != null) {
                    MyApp application = (MyApp) getActivity().getApplication();

                    if (null != application.getDatas_load()) {
                        int userId = Integer.parseInt(application.getDatas_load().getId());

                        if (userId > 0) {
                            Intent sk = new Intent(getContext(), ChannelActivateActivity.class);
                            sk.putExtra("serialNum", serialNum);
                            sk.putExtra("userId", userId);
                            startActivity(sk);
                        }
                    }

                }
            }
        }

        @Override
        public void onError(Throwable e) {
            if (e != null) {
                Log.e("----", "" + e.getMessage());
                Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onComplete() {

        }
    };

    private Observer<String> carInsuranceObserver = new Observer<String>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(String value) {
            if (!TextUtils.isEmpty(value)) {
                if (getContext() != null) {
                    Intent intent = new Intent(getContext(), HtmlActivity.class);
                    intent.putExtra("urlname", "众安车险");
                    intent.putExtra("url", value);
                    getContext().startActivity(intent);

                }
            }
        }

        @Override
        public void onError(Throwable e) {
            if (e != null) {
                Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onComplete() {

        }
    };

//    @Subscribe(threadMode = ThreadMode.MAIN)
    private void getmywallet() {
        Datas_load datasLoad = application.getDatas_load();
        if (datasLoad != null) {
            String userLogin = datasLoad.getUser_login();
            if (!TextUtils.isEmpty(userLogin)) {
                HttpMethods.getInstance().userWallet(mWalletObserver, userLogin);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Datas_event2 event) {
        Log.e("TabHomeFragment", "onEventMainThread");
        if (isVisible()) {
//            Beta.checkUpgrade ();
            onResume();

        }
    }
    @Override
    public void onDestroy() {
        Log.e("TabHomeFragment", "onEventMainThread");
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View v) {
        if (application.getDatas_load() == null) {
            aralogid("还未登录", "前往登录", 1);
            return;
        }
        if (null != application.getDatas_load().getUser_no_status()
                && application.getDatas_load().getUser_no_status()
                .equals("1")) {
//            Toast.makeText(getActivity(), "还未进行实名认证",
//                    Toast.LENGTH_SHORT).show();
            aralogid("还未实名认证", "前往认证？", 2);
        } else if (null != application.getDatas_load()
                .getUser_no_status()
                && application.getDatas_load().getUser_no_status()
                .equals("2")) {
            Toast.makeText(getActivity(), "实名认证审核中，无操作权限",
                    Toast.LENGTH_SHORT).show();
        } else {

            switch (v.getId()) {
                case R.id.chongzi_home_tv:
                    Log.e("onClick", "chongzi_home_tv");
                    Intent intent = new Intent(getContext(), CongziPassActivity.class);
                    startActivity(intent);
//                    aralogidPositive("提示","银行卡充值通道暂未开放，请前往》中财钱包》支付宝或微信扫码充值");
                    break;
                case R.id.tixian_home_tv:
                    Log.e("onClick", "tixian_home_tv");
                    Intent intent2 = new Intent(getContext(), TixianActivity.class);
                    startActivity(intent2);
                    break;
                case R.id.lay_m_scan:
                    Log.e("onClick", "lay_m_scan");
                    popupWindow2.dismiss();
                    //跳转扫一扫
                    if (getActivity() != null) {
                        IntentIntegrator.forSupportFragment(TabHomeFragment.this).setCaptureActivity(RScannerActivity.class).initiateScan();
                        //                        new IntentIntegrator(getActivity()).setCaptureActivity(RScannerActivity.class).initiateScan();
                    }
                    break;
                case R.id.lay_m_shoukuan:
                    Log.e("onClick", "shoukuan");
                    popupWindow2.dismiss();
                    dialog=Util.createLoadingDialog(getContext());
                    isZhiqing();
//                    Intent intent3 = new Intent(getContext(), ZhiqingSelectActivity.class);
//                    startActivity(intent3);
                    break;
                case R.id.lay_m_tuiguan:
                    Log.e("onClick", "lay_m_tuiguan");
                    popupWindow2.dismiss();
                    Intent intent4 = new Intent(getContext(), UserpromoteActivity.class);
                    startActivity(intent4);
                    break;
                case R.id.lay_m_xiaji:
                    popupWindow2.dismiss();
                    Log.e("onClick", "lay_m_scan");
                    Intent intn1t1 = new Intent(getContext(),
                            Userinfo_xiaActivity.class);
                    startActivity(intn1t1);
                    break;
                case R.id.xiala_main_iv:
                    Log.e("onClick", "xiala_main_iv");
                    showSelect(xiala_main_iv);
                    break;
                default:
                    break;
            }
        }
    }

    public void showSelect(View anchor) {//anchor 想让该弹出框在那个组件下显示 就传哪个组件
        Rect frame = new Rect();
        getActivity().getWindow().getDecorView()
                .getWindowVisibleDisplayFrame(frame);
        int i = 0;
        int j = 0;
        int[] location = { i, j };
        anchor.getLocationOnScreen(location);
        layoutInflater2 = LayoutInflater.from(getContext());
        popView2 = layoutInflater2.inflate(R.layout.layout_pop_type, null);
        popView2.setFocusableInTouchMode(true);
        popView2.setFocusable(true);
        LinearLayout layMScan = (LinearLayout) popView2
                .findViewById(R.id.lay_m_scan);
        LinearLayout layshoukuan = (LinearLayout) popView2
                .findViewById(R.id.lay_m_shoukuan);
        LinearLayout laytuiguan = (LinearLayout) popView2
                .findViewById(R.id.lay_m_tuiguan);
        LinearLayout layxiaji = (LinearLayout) popView2
                .findViewById(R.id.lay_m_xiaji);
        layMScan.setOnClickListener(this);
        layshoukuan.setOnClickListener(this);
        laytuiguan.setOnClickListener(this);
        layxiaji.setOnClickListener(this);
        popupWindow2 = new PopupWindow(popView2,
                android.view.ViewGroup.LayoutParams.WRAP_CONTENT/*
                                                                 * DipPxUtil.dip2px
                                                                 * (context,
                                                                 * 126)
                                                                 */,
                android.view.ViewGroup.LayoutParams.WRAP_CONTENT, true);
        //产生背景变暗效果
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = 0.4f;
        getActivity().getWindow().setAttributes(lp);
        ColorDrawable dw = new ColorDrawable(999999);
        popupWindow2.setBackgroundDrawable(dw); //如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        popupWindow2.setFocusable(true);
        popupWindow2.setOutsideTouchable(true);//点击弹出框外任意一区域弹出框消失
        popupWindow2.update();
        popupWindow2.showAsDropDown(anchor, anchor.getWidth(), 0);
        //设置popupWindow消失时的监听
        popupWindow2.setOnDismissListener(new PopupWindow.OnDismissListener() {
            //在dismiss中恢复透明度
            public void onDismiss() {
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = 1f;
                getActivity().getWindow().setAttributes(lp);
            }
        });
    }
    // 判断用户是否可直清
    private void isZhiqing() {
        AsyncHttpClient ahc = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("user_id",loaded.getId());
        Log.e("判断用户是否可直清params",params.toString());
        Log.e("判断用户是否可直清url",Constant.FMISZQ_URL);
        //url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
        ahc.post(Constant.FMISZQ_URL, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                //判断状态码获取结果
                Util.closeDialog(dialog);
                if(i == 200){
                    //
                    try {
                        String result = new String(bytes, "utf-8");
                        //                        Toast.makeText(CreditRepayActivity.this, result, Toast.LENGTH_SHORT).show();
                        Log.e("判断用户是否可直清Result", result);
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            String infro="你不是直清商户";
                            if (jsonObject.get("flag").equals("success")) {
                                if (jsonObject.has("data")){
                                    if (jsonObject.getJSONObject("data").getString("data").equals("true")){
                                                            Intent intent3 = new Intent(getContext(), ZhiqingSelectActivity.class);
                                                            startActivity(intent3);
                                                            return;
                                    }
                                }
                            }
                            aralogid("提示", "您不是直清商户", 3);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Log.e("onFailure",new String(bytes).toString());
            }
        });
    }
    // 首页文章
    private void ldScan(String qmcode) {
        AsyncHttpClient ahc = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("user_id",loaded.getId());
        params.put("qmcode",qmcode);
        Log.e("首页文章params",params.toString());
        Log.e("首页文章url",Constant.LDSCAN_URL);
        //url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
        ahc.post(Constant.LDSCAN_URL, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                //判断状态码
                Util.closeDialog(dialog);
                if(i == 200){
                    //获取结果
                    try {
                        String result = new String(bytes, "utf-8");
                        //                        Toast.makeText(CreditRepayActivity.this, result, Toast.LENGTH_SHORT).show();
                        Log.e("首页文章Result", result);
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            String infro=jsonObject.getString("info");
                            if (jsonObject.getString("flag").equals("success")) {
                                if (jsonObject.has("data")){
                                    if (jsonObject.getJSONObject("data").getJSONObject("data").getInt("status")==1){
                                        aralogid("提示","绑定成功", 3);
                                        return;
                                    }else{
                                        aralogid("提示","绑定失败", 3);
                                        return;
                                    }
                                }
                            }
                            aralogid("提示", infro, 3);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Log.e("onFailure",new String(bytes).toString());
            }
        });
    }
    // 首页文章
    private void news() {
        AsyncHttpClient ahc = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        Log.e("首页文章params",params.toString());
        Log.e("首页文章url",Constant.NEWS_URL);
        //url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
        RequestHandle post = ahc.post(Constant.NEWS_URL, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                //判断状态码
                Util.closeDialog(dialog);
                if (i == 200) {
                    //获取结果
                    try {
                        String result = new String(bytes, "utf-8");
                        //                        Toast.makeText(CreditRepayActivity.this, result, Toast.LENGTH_SHORT).show();
                        Log.e("首页文章Result", result);
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            String infro = jsonObject.getString("info");
                            if (jsonObject.getString("flag").equals("success")) {
                                if (jsonObject.has("data")) {
                                    newsData.clear();
                                    Gson gson = new Gson();
                                    String string = jsonObject.getJSONObject("data").getString("data");
                                   newsData=gson.fromJson(string, new TypeToken<ArrayList<News>>(){}.getType());
                                   Log.e("首页文章",newsData.toString()+"");
                                   newsAdapter.setData(newsData);
                                   newsAdapter.notifyDataSetChanged();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Log.e("onFailure", new String(bytes).toString());
            }
        });
    }
}
